package cn.cdiothree.service.impl;

import cn.cdiothree.dao.AuthMapper;
import cn.cdiothree.domain.auth.Role;
import cn.cdiothree.domain.auth.User;
import cn.cdiothree.domain.auth.UserDetail;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.sql.Wrapper;

/**
 * 登录身份验证
 * @author cumthing
 */
@Component(value = "CustomUserDetailsService")
@Slf4j
public class CustomUserDetailsServiceImpl implements UserDetailsService {
    private final AuthMapper authMapper;

    public CustomUserDetailsServiceImpl(AuthMapper authMapper) {
        this.authMapper = authMapper;
    }

    /**
     * 根据用户名获取用户信息
     * @param name
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetail loadUserByUsername(String name) throws UsernameNotFoundException {
        log.info("用户{}获取用户信息",name);

        User user = authMapper.selectOne(Wrappers.<User>lambdaQuery().eq(User::getName,name));

        if (user==null){
            throw new UsernameNotFoundException(String.format("No userDetail found with username '%s'.", name));
        }
        UserDetail userDetail = new UserDetail(user.getId(),user.getName(),user.getPassword(),user.getTelephone());

        Role role = authMapper.findRoleByUserId(userDetail.getId());
        userDetail.setRole(role);
        return userDetail;
    }
}
